<template>
  <el-card style="max-width: 480px;margin: 200px auto">
    <h1>用户个人信息</h1>
    <el-form :model="user" label-width="auto" style="max-width: 480px">
      <el-form-item label="昵称">
        <el-input v-model="user.nickname" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="user.email" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/upload"
            :show-file-list="false"
            :on-success="uploadSuccess"
        >
          <img v-if="user.icon" :src="user.icon" class="avatar" style="width: 80px;height: 80px;border-radius: 50%" />
          <el-icon v-else class="avatar-uploader-icon">上传头像</el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">修 改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { ElMessage } from 'element-plus'
import {mapGetters,mapActions} from "vuex";

export default {
  name: "LoginView",
  data(){
    return {
       user : {}
    }
  },
  computed:{
    ...mapGetters(['getUser']),
    suser(){
      return this.getUser
    }
  },
  mounted() {
    // this.user = JSON.parse(localStorage.getItem('user'))
    this.user = JSON.parse(JSON.stringify(this.suser))
  },
  methods:{
    ...mapActions(['loginUser']),
    //上传头像成功
    uploadSuccess(res){
      if(res.code === 200){
        this.user.icon = res.data;
      }
    },
    //修改用户
    updateUser(){
      this.$axios.put('/user',this.$qs.stringify(this.user))
          .then(result => {
            if(result.data.code === 200){
              ElMessage.success('更新成功')
              this.loginUser(this.user)
            }
          })
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>